package com.gopay.checkorder.service.impl;


import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.gopay.checkorder.service.BankOrderService;
import com.gopay.checkorder.service.task.BankCountDownLatch;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.bank.PayEaseConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.dayend.BaseDayendEntry;
import com.gopay.common.domain.bank.payease.ebank.PayEaseMessage;
import com.gopay.common.domain.cashier.BankCardType;
import com.gopay.common.domain.cps.vo.CheckOrderResult;
import com.gopay.common.domain.cps.vo.InAccInfo;
import com.gopay.common.util.DateUtils;
import com.gopay.remote.bank.BankInteractRemoteService;

/**
 * CheckOrderPayEasePayImpl.java
 * @author liuzhp
 * @2015-09-11 下午4:41:19 www.gopay.com.cn Inc.All rights reserved.
 */
public class CheckOrderPayEasePayImpl implements BankOrderService {

    private Logger logger = Logger.getLogger("PAYEASE");
    @Resource(name = "bankClient")
    private BankInteractRemoteService bankClient;
    
	@Override
	public CheckOrderResult checkOrder(BankOrder bankOrder, String target) {
		 logger.error("payease checkorder................orderid=" + bankOrder.getOrderId());
		 CheckOrderResult checkOrderResult = new CheckOrderResult();
		 checkOrderResult.setSuccess(false);
	        checkOrderResult.setOrderId(bankOrder.getOrderId());
	        PayEaseMessage message = new PayEaseMessage();
	        message.setOrderId(bankOrder.getOrderId());
	        message.setBankOrderId(bankOrder.getOutOrderId());
	        message.setBank(BankConstants.BANK_LOGO_PAYEASE);
	        message.setBankIntrChann(BisBankInterfaceChannel.get(bankOrder.getInterfaceChennelCode()));
	        message.setBankBusProd(BisBankBusinessProd.get(bankOrder.getBankBizProdCode()));
	        message.setOrderDate(DateUtils.format(bankOrder.getSendBankTm(),"yyyyMMddHHmmss"));//发往银行交易时间
	        message.setBank(bankOrder.getBankCode());
	        Result result = new Result();
	        try {
	            result = bankClient.query(message);
		        if (result == null || !result.isSuccess()) {
		            logger.error("bankClient fail.");
					if(result ==null || ProcCodeConstants.PROC_CODE_100E6037.equals(result.getResultCode())){
						BankCountDownLatch.failIncrease(bankOrder.getBankCode());
						checkOrderResult.setCommunicateError(true);
					}					
		            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
		            checkOrderResult.setErrMsg("系统返回对账结果为空");
		            return checkOrderResult;
		        }	
		        PayEaseMessage res = (PayEaseMessage) result.getDefaultModel();
		        if (res == null) {
		            // 查询订单为空
		            logger.error("fail:orderId:" + bankOrder.getOrderId() + " errcode:" + ProcCodeConstants.PROC_CODE_100E5062+ " err:bis query is null.");
		            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
		            checkOrderResult.setErrMsg("银行返回对账结果为空");
		        }
		        if (StringUtils.isEmpty(res.getVpstatus())) {
		        	// 查询订单错误
	                logger.error("b2b fail:orderId:" + bankOrder.getOrderId() + " errcode:" + result.getResultCode() + " err:"
	                        + "查询订单错误");
	                checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E5062);
	                checkOrderResult.setErrMsg("查询订单失败");
	                return checkOrderResult;
		        }
		        //成功
		        if (res.getVpstatus() != null && res.getVpstatus().equals(PayEaseConstants.QUERY_VPSTATUS_SUCCESS)) {
		        	checkOrderResult.setSuccess(true);
		            InAccInfo accInfo = new InAccInfo();
			        accInfo.setOrderId(bankOrder.getOrderId());
			        accInfo.setAmount(new BigDecimal(res.getVamount()));
			        accInfo.setRetCode("00");
			        accInfo.setCardType(BankCardType.Unknown.toString());	
			        checkOrderResult.setAccInfo(accInfo);
		            logger.error("PAYEASE订单: " + bankOrder.getOrderId() + "交易成功, "+"返回码：" + res.getVpstatus());		            
		        }
		        //处理中
		        else if (Arrays.asList(PayEaseConstants.QUERY_VPSTATUS_UNCERTAINTY.split(",")).contains(res.getVpstatus())){
		        	// 银行订单状态为处理中
		            logger.error("PAYEASE订单: " + bankOrder.getOrderId() + "的交易处理中, 返回码：" + res.getVpstatus());
		            checkOrderResult.setErrMsg(res.getVpstring());
		        }
		        //失败处理
		        else {
		        	checkOrderResult.setBankFailure(true);
		            logger.error("PAYEASE订单: " + bankOrder.getOrderId() + "的交易失败, 返回码：" + res.getVpstatus());
		            checkOrderResult.setErrMsg(res.getVpstring());
		        }
			    return checkOrderResult;
	        } catch (Exception e) {
	            logger.error("bankClient fail.", e);
	            checkOrderResult.setErrCode(ProcCodeConstants.PROC_CODE_100E6022);
	            checkOrderResult.setErrMsg("银行对账异常");
	            return checkOrderResult;
	        }
	}

	@Override
	public BankOrder getDbOrder() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public BaseMessage dayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<CheckOrderResult> checkDayend(String bank_bus) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result getDayendMsg(String string) {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public CheckOrderResult checkDayendOrder(BaseDayendEntry bdm, BankOrder bo) {
		// TODO Auto-generated method stub
		return null;
	}

}
